//
//  SCCarMaintenTable.m
//  Shuaiche
//
//  Created by liyanan on 2019/8/6.
//  Copyright © 2019 zzs. All rights reserved.
//

#import "SCCarMaintenTable.h"
#import "SCCarMaintenReportCell.h"
#import <Masonry.h>

@interface SCCarMaintenTable() <UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UILabel *headerLab;
@property (strong, nonatomic) NSMutableArray *dataArray;
@property (assign, nonatomic) BOOL showMore;  //更多按钮是否显示
@property (strong, nonatomic) UIStackView *stackView;
@property (nonatomic, assign) BOOL showFooterView; //是否展示 footerView, 默认高度为80
@property (assign, nonatomic) BOOL isOpen; //是否展开数据
@property (nonatomic, strong) NSMutableArray *btnArray;

@end

@implementation SCCarMaintenTable
NSString *reuseIden = @"SCCarMaintenReportCell";
- (instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style {
    self = [super initWithFrame:frame style:style];
    if (self) {
        [self setUpTableView];
    }
    return self;
}
- (void)setUpTableView {
    self.showMore = NO; //默认不展示
    self.bounces = NO;
    self.delegate = self;
    self.dataSource = self;
    self.rowHeight = 60;
    self.sectionHeight = 53;
    self.moreHeight = 40;
    self.footerHeight = 80;
    self.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.backgroundColor = SC_Color_BG;
    [self registerNib:[UINib nibWithNibName:reuseIden bundle:nil] forCellReuseIdentifier:reuseIden];
}
- (void)footerBtnClick:(UIButton *)sender {
    if ([_tableDelegate respondsToSelector:@selector(footerViewBtnClick:)]) {
        [_tableDelegate footerViewBtnClick:sender.tag];
    }
}

-(NSMutableArray *)btnArray {
    if (!_btnArray) {
        _btnArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _btnArray;
}
-(void)setFooterHeight:(CGFloat)footerHeight {
    _footerHeight = footerHeight;
    self.tableFooterView.frame = CGRectMake(0, 0, self.frame.size.width, footerHeight);
}

- (void)showFooterViewWithBtnTitles:(NSArray *)btnTitles btnHeight:(CGFloat)btnHeight footerHeight:(CGFloat)footerHeight configBtns:(nullable void(^)(NSArray *btns)) configBtnBlcok{
    _showFooterView = btnTitles.count>0;
    _footerHeight = footerHeight;
    
    if (_showFooterView) {
        UIStackView *stackView = [[UIStackView alloc] init];
        stackView.axis = UILayoutConstraintAxisHorizontal;
        stackView.distribution = UIStackViewDistributionFillEqually;
        stackView.alignment = UIStackViewAlignmentFill;
        stackView.spacing = 10;
        self.stackView = stackView;
        UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kSCScreenWidth, footerHeight)];
        for (int i = 0; i<btnTitles.count; i++) {
            UIButton *btn = [[UIButton alloc] init];
            [btn setTitle:btnTitles[i] forState:0];
            [btn setTitleColor:SC_TextBlack_Primary forState:0];
            btn.titleLabel.font = SC_FONT(15);
            btn.layer.cornerRadius = 4;
            btn.tag = i+1;
            btn.layer.backgroundColor = SC_HEX(0xFEE24A).CGColor;
            [btn addTarget:self action:@selector(footerBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            [self.btnArray addObject:btn];
            [stackView addArrangedSubview:btn];
        }
        [footer addSubview:stackView];

        [stackView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(footer).offset(10);
            make.right.equalTo(footer).offset(-10);
            make.bottom.equalTo(footer);
            make.height.equalTo(@(btnHeight));
        }];
        if (configBtnBlcok) {
            configBtnBlcok(self.btnArray);
        }
        self.tableFooterView = footer;
    }
}
- (void)showFooterBtnAtIndex:(NSInteger)index isShow:(BOOL)isShow{
    if (self.btnArray.count > index-1) {
        ((UIButton *)self.btnArray[index-1]).hidden = !isShow;
    }
}
-(void)setShowFooterView:(BOOL)showFooterView {
    _showFooterView = showFooterView;
}

-(void)reloadTableView:(NSMutableArray *)dataArray totalCount:(NSInteger)totalCount  updateConstraints: (nullable void(^)(CGFloat height)) updateTableHeight{
    _dataArray = dataArray;
    _totalCount = totalCount;
    if (!_isOpen) { //未展开 总条数大于展示条数 显示展开按钮
        _showMore = totalCount > _showCount;
    }else {
        _showMore = NO;
    }
    if (updateTableHeight) {
        CGFloat moreHei = _showMore ? _moreHeight: 0;
        CGFloat footerHeight = _showFooterView ? _footerHeight : 0;
        CGFloat tableHeight = _sectionHeight + dataArray.count*60 + moreHei + footerHeight;
        updateTableHeight(tableHeight);
    }
    [self reloadData];
}
- (UILabel *)headerLab {
    if (!_headerLab) {
        _headerLab = [[UILabel alloc] init];
        _headerLab.backgroundColor = SC_Color_BG;
        _headerLab.text = @"帅车内采已为您匹配了8条维保记录";
        _headerLab.textColor = SC_TextBlack_Third;
        _headerLab.font = SC_FONT(12);
        _headerLab.textAlignment = NSTextAlignmentCenter;
    }
    return _headerLab;
                          
}
#pragma mark- UITableViewDelegate, UITableViewDataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_showMore && indexPath.row == _dataArray.count) { //更多按钮显示
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"cell"];
        cell.textLabel.center = cell.center;
        cell.textLabel.text = self.moreTitle ? self.moreTitle : @"展开";
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
        cell.textLabel.textColor = SC_HEX(0xF99802);
        cell.textLabel.font = SC_FONT(12);
        cell.separatorInset = UIEdgeInsetsMake(1, 0, 0, 0);
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    SCCarMaintenReportCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIden forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = self.dataArray[indexPath.row];
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_dataArray.count) { //有记录
        return _dataArray.count+(_showMore ? 1 : 0);
    }
    return _dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_showMore) {
        return indexPath.row == _dataArray.count ? self.moreHeight : 60;
    }
    return 60;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (self.dataArray.count) {
        self.headerLab.text = [NSString stringWithFormat:@"帅车内采已为您匹配了%ld条维保记录",self.totalCount];
    }else {
        self.headerLab.text = @"帅车内采暂未匹配到维保记录";
    }
    _headerLab.backgroundColor = self.sectionBgColor ? self.sectionBgColor : SC_Color_BG;
    return self.headerLab;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return self.sectionHeight;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([_tableDelegate respondsToSelector:@selector(showMaintenanceDetailWithModel:isShowMore:)]) {
        if (_showMore && indexPath.row == self.dataArray.count) {
            if (!_alwaysShowMore) {
                self.showMore = NO; //展开所有记录
                self.isOpen = YES;
            }
            [_tableDelegate showMaintenanceDetailWithModel:nil isShowMore:YES];
        }else {
            SCMaintenanceModel *model = self.dataArray[indexPath.row];
            [_tableDelegate showMaintenanceDetailWithModel:model isShowMore:NO];
        }
    }
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    cell.backgroundColor = UIColor.clearColor;
    NSInteger count = _showMore ? _dataArray.count : _dataArray.count-1;
    if (count == 0) {
         [cell.layer insertSublayer:[self setCellLayerWithRect:cell.bounds corners:UIRectCornerTopLeft | UIRectCornerTopRight | UIRectCornerBottomLeft | UIRectCornerBottomRight] atIndex:0];
    }else {
        
        if (indexPath.row == 0) {
            [cell.layer insertSublayer:[self setCellLayerWithRect:cell.bounds corners:UIRectCornerTopLeft | UIRectCornerTopRight] atIndex:0];
        }else if (indexPath.row == count) {
            [cell.layer insertSublayer:[self setCellLayerWithRect:cell.bounds corners:UIRectCornerBottomLeft | UIRectCornerBottomRight] atIndex:0];
        }else {
            cell.backgroundColor = UIColor.whiteColor;
        }
    }
}


- (CAShapeLayer *)setCellLayerWithRect: (CGRect)rect corners: (UIRectCorner)corners {
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:corners cornerRadii:CGSizeMake(4, 4)];
    CAShapeLayer *layer = [[CAShapeLayer alloc] init];
    layer.path = path.CGPath;
    layer.fillColor = UIColor.whiteColor.CGColor;
    return layer;
}

@end
